package com.ship.dispatch.service.fob.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.dispatch.bean.SpDispatchSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.SpPortInformation;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.utils.TemplateParamUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.mapper.SpPortInformationMapper;
import com.ship.dispatch.mapper.fob.SpFobCzqrldlxzlMapper;
import com.ship.dispatch.mapper.fob.SpFobFsxzhczlMapper;
import com.ship.dispatch.service.SpDispatchSchemeDetailService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobCzqrldlxzlService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpFobQrxzgService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yl
 * @title SpFobCzqrldlxzlServiceImpl
 * @description 与船长确认留底量和卸载
 * @create 2023/12/18 0018
 */
@Service
public class SpFobCzqrldlxzlServiceImpl extends FobBaseServiceImpl<SpFobCzqrldlxzlMapper,SpFobCzqrldlxzl> implements SpFobCzqrldlxzlService {

    @Autowired(required = false)
    SpFobCzqrldlxzlMapper mapperapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;

    @Autowired
    SpFobTemplateService spFobTemplateService;
    @Autowired(required = false)
    SpPortInformationMapper spPortInformationMapper;

    @Autowired
    SpDispatchSchemeDetailService spDispatchSchemeDetailService;

    @Autowired
    SpFobQrxzgService spFobQrxzgService;

    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobCzqrldlxzl object = JsonUtils.jsonToObject(json,SpFobCzqrldlxzl.class);
        SpFobCzqrldlxzl his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobCzqrldlxzl>().eq(SpFobCzqrldlxzl::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobCzqrldlxzl::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            mapperapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            BeanUtils.copyProperties(object,his);
            mapperapper.updateById(his);
            his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobCzqrldlxzl>().eq(SpFobCzqrldlxzl::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobCzqrldlxzl::getStatus,-2));

            // 处理多余文件记录
            if((his.getFiels()!=null && his.getFiels().length()>0) || (his.getXzFiels()!=null && his.getXzFiels().length()>0)){
                String temp = his.getFiels();
                if(his.getXzFiels()!=null && temp!=null){
                    temp = temp+","+his.getXzFiels();
                }else if(temp==null && his.getXzFiels()!=null){
                    temp = his.getXzFiels();
                }
                String[] fieldIds = temp.split(",");
                List<String> ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
                spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
            }
        }
    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return mapperapper.selectOne(new LambdaQueryWrapper<SpFobCzqrldlxzl>().eq(SpFobCzqrldlxzl::getProceeInstanceId,id).ne(SpFobCzqrldlxzl::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobCzqrldlxzl spFob = new SpFobCzqrldlxzl();
        BeanUtils.copyProperties(bean,spFob);
        this.save(spFob);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobCzqrldlxzl spFob = new SpFobCzqrldlxzl();
        BeanUtils.copyProperties(bean,spFob);
        this.updateById(spFob);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobCzqrldlxzl spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = mapperapper.selectById(serviceId);
        }else {
            spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobCzqrldlxzl>().eq(SpFobCzqrldlxzl::getProceeInstanceId,id).ne(SpFobCzqrldlxzl::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        if(spFobZzgcjr.getXzFiels()!=null){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("xzFiels",spFobFileRecordList);
        }
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if (execute.getExpectedUnloadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedUnloadingPort());
        }
        return map;
    }



    @Override
    public String  getTemplateParam(ManageEntityVo manageEntityVo) {
        ObjectNode json = manageEntityVo.getData();
        SpFobCzqrldlxzl spFobZzgcjr = JsonUtils.jsonToObject(JsonUtils.objectToJson(json),SpFobCzqrldlxzl.class);
        SpFobQrxzg  spFobQrxzg = spFobQrxzgService.findData(manageEntityVo.getProcessInstanceId());

        // 调度方案信息
        SpDispatchSchemeExecute schemeDetail = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
        Map<String,String> map = new HashMap<>();
        if(schemeDetail!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(schemeDetail),String.class);
            for(String key:tempMap.keySet()){
                map.put("spDispatchSchemeDetail."+key,tempMap.get(key));
            }
        }
        SpPortInformation spPortInformation  = null;
        if(spFobQrxzg!=null && spFobQrxzg.getExpectedUnloading()!=null){
            spPortInformation  = spPortInformationMapper.selectById(spFobQrxzg.getExpectedUnloading());
        }
        else if(schemeDetail.getExpectedUnloadingPort()!=null){ // 获取港口信息
            spPortInformation = spPortInformationMapper.selectOne(new LambdaQueryWrapper<SpPortInformation>()
                    .eq(SpPortInformation::getPortNameEnglish,schemeDetail.getExpectedUnloadingPort())
                    .or().eq(SpPortInformation::getPortNameChinese,schemeDetail.getExpectedUnloadingPort())
                    .last("LIMIT 1")
            );
        }
        if(spPortInformation!=null){
            map.put("spDispatchSchemeDetail.expectedUnloadingPort",spPortInformation.getPortNameEnglish());
            map.put("spPortInformation.portCountry",spPortInformation.getPortCountry());
        }else{
            map.put("spPortInformation.portCountry","");
        }
        String  templateId = null;
        if("FOB001-12-01".equals(manageEntityVo.getFormKey()) || "FOB004-12-01".equals(manageEntityVo.getFormKey())){
            templateId = spFobZzgcjr.getTemplateId();
            // 查询当前近一次航行
            //new LambdaQueryWrapper<>()
            //            .eq(SpDispatchSchemeDetail::getPlanId,schemeDetail.getPlanId())
            //             .eq(SpDispatchSchemeDetail::getSchemeId,schemeDetail.getSchemeId())
            List<SpDispatchSchemeDetail> schemes = spDispatchSchemeDetailService.list(new LambdaQueryWrapper<SpDispatchSchemeDetail>()
                    .eq(SpDispatchSchemeDetail::getPlanId,schemeDetail.getPlanId())
                    .eq(SpDispatchSchemeDetail::getSchemeId,schemeDetail.getSchemeId())
                    .gt(SpDispatchSchemeDetail::getExpectedLoadingDate,schemeDetail.getExpectedLoadingDate())
                    .orderByAsc(SpDispatchSchemeDetail::getExpectedLoadingDate)
                    .last("limit 1")
            );
            if(schemes.size()>0){
                SpDispatchSchemeDetail next = schemes.get(0);
                if(next.getExpectedUnloadingPort()!=null){
                    map.put("spDispatchSchemeDetail.expectedUnloadingPort1",next.getExpectedUnloadingPort());
                    spPortInformation = spPortInformationMapper.selectOne(new LambdaQueryWrapper<SpPortInformation>()
                            .eq(SpPortInformation::getPortNameEnglish,next.getExpectedUnloadingPort())
                            .or().eq(SpPortInformation::getPortNameChinese,next.getExpectedUnloadingPort())
                            .last("LIMIT 1")
                    );
                    if(spPortInformation!=null){
                        map.put("spPortInformation.portCountry1",spPortInformation.getPortCountry());
                    }else{
                        map.put("spPortInformation.portCountry1"," ");
                    }
                }
            }
        }else {
            templateId = spFobZzgcjr.getXzTemplateId();
            // 获取船运合同信息
            Map<String,Object> shipConMap = mapperapper.selectShipCon(schemeDetail.getShipContractId());
            for(String key:shipConMap.keySet()){
                String tempKey = JsonUtils.toCamelCase(key);
                map.put("conShipping."+tempKey,shipConMap.get(key)+"");
            }
        }
        if(templateId==null){
            throw  new BusException("请选模板后再生成模板正文", BaseResultCode.GENERAL_ERROR);
        }
        SpFobTemplate spFobTemplate = spFobTemplateService.getById(templateId);
        if(spFobTemplate == null){
            throw  new BusException("当前模板不存在，请联系管理员处理", BaseResultCode.GENERAL_ERROR);
        }
        // 当前业务表单信息
        if(json!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(json),String.class);
            for(String key:tempMap.keySet()){
                map.put("spFobCzqrldlxzl."+key,tempMap.get(key));
            }
        }
        String template = "";
        if(spFobTemplate !=null){
            template = TemplateParamUtils.processDynamicParams(spFobTemplate.getContent(),map);
        }
        return template;
    }

    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobCzqrldlxzl> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobCzqrldlxzl>().eq(SpFobCzqrldlxzl::getProceeInstanceId,processInstanceId).orderByDesc(SpFobCzqrldlxzl::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }

    @Override
    public SpFobCzqrldlxzl findFormData(String processInstanceId) {
        SpFobCzqrldlxzl spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobCzqrldlxzl>().eq(SpFobCzqrldlxzl::getProceeInstanceId,processInstanceId).ne(SpFobCzqrldlxzl::getStatus,-2));
        return spFobZzgcjr;
    }
}
